package com.android.nfctouch.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.android.baselibrary.interface_.OkHttpCallBack;
import com.android.baselibrary.responce.BaseResponce;
import com.android.baselibrary.tool.CommLoading;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.util.GlideEngine;
import com.android.baselibrary.util.GlideUtil;
import com.android.baselibrary.util.Util;
import com.android.baselibrary.view.Comm_EditView;
import com.android.baselibrary.view.Comm_HeadView;
import com.android.baselibrary.view.MultiStateView;
import com.android.nfctouch.R;
import com.android.nfctouch.bean.ContactInfo;
import com.android.nfctouch.bean.ContactTypeInfo;
import com.android.nfctouch.bean.UpLoadedFileInfo;
import com.android.nfctouch.constants.Constants;
import com.android.nfctouch.manager.API_HomeManager;
import com.android.nfctouch.manager.API_Manager;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import xyz.doikki.videocontroller.StandardVideoController;
import xyz.doikki.videoplayer.player.VideoView;

public class AddContactActivity extends BaseActivity {

    @BindView(R.id.multiplestatusView)
    MultiStateView multiplestatusView;
    @BindView(R.id.comm_title)
    Comm_HeadView comm_title;
    @BindView(R.id.et_content)
    Comm_EditView et_content;
    @BindView(R.id.dk_player)
    VideoView dk_player;
    @BindView(R.id.tv_tips)
    TextView tv_tips;
    @BindView(R.id.radiogroup_repeat)
    RadioGroup radiogroup_repeat;
    @BindView(R.id.iv_img)
    ImageView iv_img;

    Handler handler = new Handler();
    ContactTypeInfo contactTypeInfo;
    ContactInfo contactInfo;

    String imgUrl;
    int status; //状态 0：所有人可见   1：自己可见

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_contact;
    }

    @Override
    protected void initView() {
        radiogroup_repeat.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.tb_repeat1:
                        status = 0;
                        break;
                    case R.id.tb_repeat2:
                        status = 1;
                        break;
                }
            }
        });
    }

    @Override
    protected void initData() {
        contactTypeInfo = (ContactTypeInfo) getIntent().getSerializableExtra("contactTypeInfo");
        contactInfo = (ContactInfo) getIntent().getSerializableExtra("contactInfo");

        if (contactInfo != null) {
            //编辑
            contactTypeInfo = contactInfo.sysLinkEntity;
            et_content.setText(contactInfo.content);
            comm_title.setTitle("编辑联系方式");

            status = contactInfo.status;
            radiogroup_repeat.check(radiogroup_repeat.getChildAt(status).getId());

        } else {
            //新增
            comm_title.setTitle("新增联系方式");

        }

        iv_img.setVisibility(View.GONE);
        et_content.setVisibility(View.GONE);
        //类型：0-账号，1-链接，2-二维码	integer
        String tips = "";
        if (contactTypeInfo.type == 0) {
            tips = "请输入" + contactTypeInfo.name + "账号";

            et_content.setVisibility(View.VISIBLE);
        } else if (contactTypeInfo.type == 1) {
            tips = "请输入" + contactTypeInfo.name + "链接";
            et_content.setIsMultipleLines(true);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) et_content.getLayoutParams();
            params.height = Util.dip2px(mContext, 200);
            et_content.setLayoutParams(params);

            et_content.setVisibility(View.VISIBLE);
        } else {
            tips = "请上传" + contactTypeInfo.name + "二维码";
            if (contactInfo != null) {
                imgUrl = contactInfo.content;
                GlideUtil.displayImage(mContext, imgUrl, iv_img, 0);
            }
            iv_img.setVisibility(View.VISIBLE);
        }
        tv_tips.setText(tips);
        bindData();
    }

    @OnClick({R.id.csb_submit, R.id.iv_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.csb_submit:
                if (contactInfo != null) {
                    //编辑
                    home_contact_update();
                } else {
                    //新增
                    add();
                }
                break;
            case R.id.iv_img:
                getPic();
                break;
        }
    }

    //新增
    private void add() {
        String content = et_content.getText();
        if (contactTypeInfo.type == 2) {
            content = imgUrl;
        }
        API_HomeManager.home_contact_add(mContext, content, contactTypeInfo.linkId, status, new OkHttpCallBack<BaseResponce<String>>() {
            @Override
            public void onSuccess(BaseResponce<String> baseResponce) {
                CommToast.showToast(mContext, "添加成功");
                finish();
            }

            @Override
            public void onFailure(BaseResponce<String> baseResponce) {
                multiplestatusView.setViewState(MultiStateView.ViewState.ERROR);
                CommToast.showToast(mContext, Constants.NetError);
            }
        });
    }

    //编辑
    private void home_contact_update() {
        String content = et_content.getText();
        if (contactTypeInfo.type == 2) {
            content = imgUrl;
        }
        API_HomeManager.home_contact_update(mContext, content, contactInfo.userLinkId, status, new OkHttpCallBack<BaseResponce<String>>() {
            @Override
            public void onSuccess(BaseResponce<String> baseResponce) {
                CommToast.showToast(mContext, "修改成功");
                finish();
            }

            @Override
            public void onFailure(BaseResponce<String> baseResponce) {
                multiplestatusView.setViewState(MultiStateView.ViewState.ERROR);
                CommToast.showToast(mContext, Constants.NetError);
            }
        });
    }

    private void bindData() {
        dk_player.setUrl(contactTypeInfo.videoUrl); //设置视频地址
        StandardVideoController controller = new StandardVideoController(mContext);
        controller.addDefaultControlComponent("", false);
        dk_player.setVideoController(controller); //设置控制器
        dk_player.start(); //开始播放，不调用则不自动播放
    }


    //修改背景
    private void getPic() {
        String[] permissions = new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        //是否永久拒绝了权限
        boolean isPermanentDenied = XXPermissions.isPermanentDenied((Activity) mContext, permissions);
        XXPermissions.with(mContext).permission(permissions).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                //权限允许
                PictureSelector.create(mContext)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(1)  //一次最多选几张图
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result1) {
                                LocalMedia media = result1.get(0);
                                Log.i("media.getPath():" + media.getRealPath());
                                common_upload(new File(media.getRealPath()), 3);
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                //权限被拒绝
                if (never) {
                    if (isPermanentDenied)  //永久拒绝了，只能跳系统设置页打开
                    {
                        XXPermissions.startPermissionActivity(mContext, permissions);
                        Toast.makeText(mContext, "您已经拒绝了相册权限，需要在系统设置中将权限打开后重试", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(mContext, "您拒绝了相册权限，无法使用相册功能", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    //上传文件  type: 1-头像，2-背景，3-通用
    private void common_upload(File file, int type) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                CommLoading.showLoading((FragmentActivity) mContext);
            }
        }, 200);
        API_Manager.common_upload(mContext, file, type, new OkHttpCallBack<BaseResponce<UpLoadedFileInfo>>() {
            @Override
            public void onSuccess(BaseResponce<UpLoadedFileInfo> baseResponce) {
                Log.i("path:" + baseResponce.data.path);
                UpLoadedFileInfo fileInfo = baseResponce.data;
                CommLoading.dismissLoading();
                imgUrl = fileInfo.path;
                GlideUtil.displayImage(mContext, imgUrl, iv_img, 0);
            }

            @Override
            public void onFailure(BaseResponce<UpLoadedFileInfo> baseResponce) {
                CommLoading.dismissLoading();
                CommToast.showToast(mContext, Constants.NetError);
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        dk_player.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        dk_player.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dk_player.release();
    }

    @Override
    public void onBackPressed() {
        if (!dk_player.onBackPressed()) {
            super.onBackPressed();
        }
    }
}
